﻿const STORAGE_MANAGER =
{
    searchword: "sessionstoragekey_searchword"                       // 查询关键字
    , searchhistory: "localstoragekey_searchhistory"                // 搜索历史纪录
    , ordersearchhistory: "localstoragekey_ordersearchhistory"        //  订单搜索历史
    , searchtag: "localstoragekey_searchtag"                         // 搜索框中随机显示二级分类名称
    , user: "user"
    , currentmember: "localstoragekey_currentmember"               // 当前会员信息
    , customerInfo: "customerInfo"
    , storeageTime: "localstoragekey_storeageTime"                  // 缓存时间
    , category: "localstoragekey_category"                           // 分类缓存数据（1天有效）
    , parentcategory: "localstoragekey_parentcategory"             // 父类缓存数据（1天有效）
    , cacheproductcount: "cacheProductCount"                        // 购物车中商品的个数
    , lastCheckTime: "localstoragekey_lastCheckTime"              // 最后查看时间
    , showwelcome: "localstoragekey_showwelcome"                  // 是否已经显示了欢迎页
    , barcodehistory: "localstoragekey_barcodehistory"            // 二维码扫描历史
    , ip: "localstoragekey_ip"                                        // IP地址
    , reciveMessageSetting: "recive_message_setting"             //是否接收推送消息
    , bellsSetting: "bell_setting"                                  //以铃声提示
    , shakeSetting: "shake_setting"                                 //以震动提示
    , is_show_download_div: "sessionstoragekey_is_show_download_div"      // 是否关闭下载浮层
    , username: "login_user_name" //登陆用户名
    , confirmOrderData: "confirm_order_data" //确认订单数据
    , activeTab: "localstoragekey_activeTab" // 当前Tab
    , latestversion: "localstoragekey_latestversion"
    , issetpaypasswd: "is_set_paypasswd" 							//是否设置支付密码
}

const ISDEBUG = true;
// 互斥
const AGENT_CLIENT =
{
    APP: !ISDEBUG,
    WEB: ISDEBUG
}

$(function () {
    //显示等待中
    $.showWaiting = function (message) {
        if ($("#message_waiting_pop").length > 0) {
            return;
        }
        var html = [];
        html.push("<div id='message_waiting_pop' class='pop-wrap'  style='background: transparent;'>");
        html.push("<div class='waiting'>");
        if (message) {
            html.push("<div class='msgtop1'></div>");
            html.push("<div class='spinner spinner1'>");
        } else {
            html.push("<div class='msgtop2'></div>");
            html.push("<div class='spinner spinner2'>");
        }
        html.push("<div class='bar1'></div>");
        html.push("<div class='bar2'></div>");
        html.push("<div class='bar3'></div>");
        html.push("<div class='bar4'></div>");
        html.push("<div class='bar5'></div>");
        html.push("<div class='bar6'></div>");
        html.push("<div class='bar7'></div>");
        html.push("<div class='bar8'></div>");
        html.push("<div class='bar9'></div>");
        html.push("<div class='bar10'></div>");
        html.push("<div class='bar11'></div>");
        html.push("<div class='bar12'></div>");
        html.push("</div>");
        if (message) {
            html.push("<div class='msgbottom1 waitingmessage'>" + message + "</div>");
        } else {
            html.push("<div class='msgbottom2'></div>");
        }
        html.push("</div>");
        html.push("</div>");
        html = html.join('');
        $(html).appendTo("body");
    }

    $.closeWaiting = function () {
        if ($("#message_waiting_pop").length > 0) {
            $("#message_waiting_pop").remove();
            return;
        }
    }

    $.alert = function (message, alertCB, title, buttonCapture) {
        if ($("#message_alert_pop").length > 0) {
            return;
        }
        // 默认值
        if (!title) {
            title = "";
        }
        if (!message) {
            message = "";
        }
        if (!buttonCapture) {
            buttonCapture = "好";
        }

        var html = "<div id='message_alert_pop' class='pop-wrap'><div class='passwrod-bank-inp'><h2>{0}</h2><pre class='tishiyu'>{1}</pre><div class='pass-btn-block'><p class='queding1' id='btnalert0'>{2}</p></div></div></div>";

        html = html.format(title, message, buttonCapture);
        $(html).appendTo("body");

        $("#btnalert0").on("click", function () {
            $("#message_alert_pop").remove();
            if (alertCB) alertCB(0);
        });
    };

    $.confirm = function (message, confirmCB, title, buttons) {
        if ($("#message_confirm_pop").length > 0) {
            return;
        }
        // 默认值
        if (!title) {
            title = "";
        }
        if (!message) {
            message = "";
        }
        if (!buttons) {
            buttons = ["确定", "取消"];
        } else if (buttons.length < 2) {
            $(alert(message, confirmCB, title, buttons[0]));
        }

        var html = "<div id='message_confirm_pop' class='pop-wrap' ><div class='passwrod-bank-inp' style='min-width: 17em;'><h2>{0}</h2><pre class='tishiyu'>{1}</pre><div class='pass-btn-block'><p class='queding' id='btnconfrim0'>{2}</p><p class='quxiao' id='btnconfrim1'>{3}</p></div></div></div>";
        html = html.format(title, message, buttons[0], buttons[1]);
        $(html).appendTo("body");

        var pop = $("#message_confirm_pop");
        $("#btnconfrim0").on("click", function () {
            if (confirmCB) confirmCB(0);
            pop.remove();
        });
        $("#btnconfrim1").on("click", function () {
            if (confirmCB) confirmCB(1);
            pop.remove();
        });
    };

    $.prompt = function (message, promptCB, title, tip, buttons) {
        if (AGENT_CLIENT.APP && window.plus) {
            plus.nativeUI.prompt(message, promptCB, title, buttons);
            return;
        }
        if ($("#message_prompt_pop").length > 0) {
            return;
        }
        // 默认值
        if (!title) {
            title = "";
        }
        if (!message) {
            message = "";
        }
        if (!tip) {
            tip = "";
        }
        if (!buttons || buttons.length < 2) {
            buttons = ["确定", "取消"];
        }

        var html = "<div class='pop-wrap' id='message_prompt_pop'><div class='passwrod-bank-inp' style='min-width: 17em;'><h2>{0}</h2><pre class='tishiyu'>{1}</pre><p class='srxmk'><input type='text' id='message_prompt_input' class='qsrndxm' placeholder='{2}'></p><div class='pass-btn-block'><p class='queding' id='btnprompt0'>{3}</p><p class='quxiao' id='btnprompt1'>{4}</p></div></div></div>";
        html = html.format(title, message, tip, buttons[0], buttons[1]);
        $(html).appendTo("body");

        $("#message_prompt_input").focus();

        var pop = $("#message_prompt_pop");
        $("#btnprompt0").on("tap", function () {
            var value = $("#message_prompt_input").val();
            pop.remove();
            if (promptCB) promptCB(0, value);
        });
        $("#btnprompt1").on("tap", function () {
            var value = $("#message_prompt_input").val();
            pop.remove();
            if (promptCB) promptCB(1, value);
        });
    };

    $.toast = function (message) {
        // 默认值
        if (!message) {
            message = "";
        }
        var options = {
            duration: 1000,
            top: "",
            left: ""
        };

        var html = "<div name='message_toast' class='pop-wrap' style='background: transparent;pointer-events: none;'><i class='toastmsg'>{0}</i></div>";
        html = html.format(message);
        $(html).appendTo("body");

        var msg = $("div[name=message_toast]");
        msg.fadeIn(1000);
        setTimeout(function () {
            msg.fadeOut(1200);
            setTimeout(function () {
                msg.remove();
            }, 1500);
        }, options.duration);
    };

    // 获取IP
    $.getIPAddress = function (refresh) {
        var ip = getLocalStorage(STORAGE_MANAGER.ip);
        if (!ip || refresh) {
            $.getScript("http://pv.sohu.com/cityjson?ie=utf-8").done(function () {
                setLocalStorage(STORAGE_MANAGER.ip, returnCitySN.cip);
                return returnCitySN.cip;
            }).fail(function (res) {
                setLocalStorage(STORAGE_MANAGER.ip, "127.0.0.1");
                return "127.0.0.1";
            });
        } else {
            return ip;
        }
    }

});

/**
 * Github: https://github.com/BR0kEN-/jTap
 */
(function ($, _) {
    'use strict';
    var isTouch = "ontouchend" in document.createElement("div");
    var ev = {
        start: isTouch ? 'touchstart' : 'mousedown',
        end: isTouch ? 'touchend' : ' mouseup'
    };

    $.event.special[_] = {
        setup: function () {
            $(this).off('click').on(ev.start + ' ' + ev.end, function (e) {
                ev.E = e.originalEvent.changedTouches ? e.originalEvent.changedTouches[0] : e;
            }).on(ev.start, function (e) {

                if (e.which && e.which !== 1) {
                    return;
                }
                ev.target = e.target;
                ev.time = new Date().getTime();
                ev.X = ev.E.pageX;
                ev.Y = ev.E.pageY;
            }).on(ev.end, function (e) {
                if (
                    ev.target === e.target &&
                    ((new Date().getTime() - ev.time) < 750) &&
                    (ev.X === ev.E.pageX && ev.Y === ev.E.pageY)
                ) {

                    e.type = _;
                    e.pageX = ev.E.pageX;
                    e.pageY = ev.E.pageY;

                    $.event.dispatch.call(this, e);
                }
            });
        },
        remove: function () {
            $(this).off(ev.start + ' ' + ev.end);
        }
    };

    $.fn[_] = function (fn) {
        return this[fn ? 'on' : 'trigger'](_, fn);
    };
})(jQuery, 'tap');


/**
 * $.os
 * @param {type} $
 * @returns {undefined}
 */
(function ($, window) {
    function detect(ua) {
        this.os = {};
        var funcs = [

            function () { //wechat
                var wechat = ua.match(/(MicroMessenger)\/([\d\.]+)/i);
                if (wechat) { //wechat
                    this.os.wechat = {
                        version: wechat[2].replace(/_/g, '.')
                    };
                }
                return false;
            },
            function () { //android
                var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/);
                if (android) {
                    this.os.android = true;
                    this.os.version = android[2];

                    this.os.isBadAndroid = !(/Chrome\/\d/.test(window.navigator.appVersion));
                }
                return this.os.android === true;
            },
            function () { //ios
                var iphone = ua.match(/(iPhone\sOS)\s([\d_]+)/);
                if (iphone) { //iphone
                    this.os.ios = this.os.iphone = true;
                    this.os.version = iphone[2].replace(/_/g, '.');
                } else {
                    var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
                    if (ipad) { //ipad
                        this.os.ios = this.os.ipad = true;
                        this.os.version = ipad[2].replace(/_/g, '.');
                    }
                }
                return this.os.ios === true;
            }
        ];
        [].every.call(funcs, function (func) {
            return !func.call($);
        });
    }

    detect.call($, navigator.userAgent);
})(window, window);

String.prototype.Trim = function(is_global){
    var result;
    result = this.replace(/(^\s+)|(\s+$)/g,"");
    if(is_global.toLowerCase()=="g")
    {
        result = result.replace(/\s/g,"");
     }
    return result;	
}

//实现字符串trime
function Trim(str,is_global)
{
    var result;
    result = str.replace(/(^\s+)|(\s+$)/g,"");
    if(is_global.toLowerCase()=="g")
    {
        result = result.replace(/\s/g,"");
     }
    return result;
}

//实现字符串format功能
String.prototype.format = function (args) {
    var result = this;
    if (arguments.length > 0) {
        if (arguments.length == 1 && typeof(args) == "object") {
            for (var key in args) {
                if (args[key] != undefined) {
                    var reg = new RegExp("({" + key + "})", "g");
                    result = result.replace(reg, args[key]);
                }
            }
        } else {
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i] != undefined) {
                    var reg = new RegExp("({[" + i + "]})", "g");
                    result = result.replace(reg, arguments[i]);
                }
            }
        }
    }
    return result;
}

//实现Date的format功能例如：(new Date()).Format('yyyy-MM-dd hh:mm:ss');
Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

//timespan转换成时间字符串例如：toDateString(1442963412, 'yyyy-MM-dd hh:mm:ss')
function toDateString(timespan, fmt) {
    var newDate = new Date();
    newDate.setTime(timespan * 1000);
    return newDate.Format(fmt);
}

// 设置localstorage
function setLocalStorage(key, value) {
    localStorage.setItem(key, JSON.stringify(value));
}

// 读取localstorage
function getLocalStorage(key) {
    var obj = localStorage.getItem(key);
    if (obj) {
        return JSON.parse(obj);
    }
    return null;
}

//删除localstorage
function removeLocalStorage(key) {
    localStorage.removeItem(key);
}

// 设置sessionstorage
function setSessionStorage(key, value) {
    sessionStorage.setItem(key, JSON.stringify(value));
}

// 读取sessionstorage
function getSessionStorage(key) {
    var obj = sessionStorage.getItem(key);
    if (obj) {
        return JSON.parse(obj);
    }
    return null;
}

//删除sessionstorage
function removeSessionStorage(key) {
    sessionStorage.removeItem(key);
}

// localStorage
function setPageParams(pagename, value) {
    localStorage.setItem(pagename, JSON.stringify(value));
}

// 读取页面参数(读取一次会删除)localStorage
function getPageParams(pagename) {
    var obj = localStorage.getItem(pagename);
    if (obj) {
        localStorage.removeItem(pagename);
        return JSON.parse(obj);
    }
    return null;
}


// 获取URL中参数
function getUrlParam(name, url) {
    var paramstr = url ? url.substr(url.lastIndexOf('?')) : window.location.search;
    paramstr = decodeURI(paramstr);
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = paramstr.substr(1).match(reg); //匹配目标参数
    if (r != null) return unescape(r[2]);
    return null; //返回参数值
}

// 获取跳转文件名
function getUrlFileName(strUrl) {
    var arrUrl = strUrl.split("/");
    var strPage = arrUrl[arrUrl.length - 1];

    return strPage;
}

// 生成唯一GUID
function NewGuid() {
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());

    function S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }
}




// 产生随机数
function getRandomNum(min, max) {
    var range = max - min;
    var rand = Math.random();
    return (min + Math.round(rand * range));
}


